//
//  MKUserModelView.m
//  Weibo_OC
//
//  Created by mac on 16/1/13.
//  Copyright © 2016年 mac. All rights reserved.
//

#import "MKUserModelView.h"

#import "MKUserAccount.h"
#import "MKNetworkTools.h"

@implementation MKUserModelView

- (BOOL)flag {
    return self.userAccount.access_token !=nil;
}

- (NSString *)name {
    return self.userAccount.name;
}

- (NSURL *)headerImageURL {

    return [NSURL URLWithString:self.userAccount.avatar_large];
}

- (NSString *)access_token {
    return self.userAccount.access_token;
}

- (instancetype)init {
    if (self = [super init]) {
        self.userAccount = [MKUserAccount loadUserInfo];
    }
    
    return self;
}

- (void)loadTokenWithCodeAtModelView:(NSString *)code andSuccess:(void (^)(bool flag))success {
    
    NSString *client_id = @"2124965822";
    NSString *redirect_uri = @"http://www.itcast.cn";
    NSString *urlString = @"oauth2/access_token";
    
    NSDictionary *dic = @{@"client_id":client_id,@"client_secret":@"dfeb5a574bd063c1d9f463e9de697eb7",@"grant_type":@"authorization_code",@"code":code,@"redirect_uri":redirect_uri};
    
    [[MKNetworkTools sharedNetworkTools] POST:urlString parameters:dic progress:nil success:^(NSURLSessionDataTask * _Nonnull task, NSDictionary * _Nullable responseObject) {
        
        MKUserAccount *model = [MKUserAccount userAccountWithDict:responseObject];
        
        [self loadUserInfoWith:model andSuccess:success];
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"%@",error);
        success(NO);
    }];
    
}

- (void)loadUserInfoWith:(MKUserAccount *)model andSuccess:(void (^)(bool))success {
    
    NSString *urlString = [NSString stringWithFormat:@"users/show.json?access_token=%@&uid=%@",model.access_token,model.uid];
    
    [[MKNetworkTools sharedNetworkTools] GET:urlString parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, NSDictionary * _Nullable responseObject) {
        
        model.uid = responseObject[@"uid"];
        model.avatar_large = responseObject[@"avatar_large"];
        model.name = responseObject[@"name"];
        
        [model saveUserInfo];
        
        //成功后回调
        success(YES);
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"%@",error);
    }];
}
@end
